package task

import (
	"errors"
	"os"
	"path"
	"path/filepath"
	"strings"
)

// 判断目录是否存在
func IsDir(fileAddr string) bool {
	s, err := os.Stat(fileAddr)
	if err != nil {
		return false
	}
	return s.IsDir()
}

type FileHandler struct {
	flow *FlowTask
}

func NewFileHandler(flow *FlowTask) *FileHandler {
	net := new(FileHandler)
	net.flow = flow
	return net
}

func (m *FileHandler) Save(node *Node) error {
	savePath := node.Content["savePath"] //保存路径
	input := m.flow.BindInput(node.Params)
	names := make([]string, 0)
	data := input["sourceFile"]
	if data != nil {
		ds, ok := data.([]map[string][]byte)
		if ok {
			for _, item := range ds {
				for k, v := range item {
					if savePath != "" {
						if !IsDir(savePath) {
							os.MkdirAll(savePath, os.ModePerm)
						}
					}
					saveFile := path.Join(savePath, k)
					err := os.WriteFile(saveFile, v, os.ModePerm)
					if err != nil {
						m.flow.errMsg = append(m.flow.errMsg, err.Error())
						break
					}
					names = append(names, k)
				}
			}
		}
		m.flow.outText[node.Id] = strings.Join(names, ",")
	}
	return nil
}

func (m *FileHandler) Move(node *Node) error {
	filePath := node.Content["filePath"] //文件路径
	savePath := node.Content["savePath"] //保存路径
	input := m.flow.BindInput(node.Params)
	filename := input["moveFileName"]
	if filename == nil {
		return errors.New("移动文件：参数中未找到文件名称")
	}
	if savePath != "" {
		if !IsDir(savePath) {
			os.MkdirAll(savePath, os.ModePerm)
		}
	}
	name := filepath.Base(filename.(string))
	err := os.Rename(path.Join(filePath, name), path.Join(savePath, name))
	if err != nil {
		return errors.New("移动文件：" + err.Error())
	}
	return nil
}

func (m *FileHandler) Delete(node *Node) error {
	filePath := node.Content["filePath"] //文件路径
	input := m.flow.BindInput(node.Params)
	filename := input["deleteFileName"]
	if filename == nil {
		return errors.New("删除文件：参数中未找到文件名称")
	}
	name := filename.(string)
	err := os.Remove(path.Join(filePath, name))
	if err != nil {
		return errors.New("删除文件：" + err.Error())
	}
	return nil
}

func (m *FileHandler) Read(node *Node) error {
	filePath := node.Content["filePath"] //文件路径
	input := m.flow.BindInput(node.Params)
	filename := input["readFileName"] //文件名称
	if filename == nil {
		return errors.New("读取文件：参数中未找到文件名称")
	}
	name := filename.(string)
	bs, err := os.ReadFile(path.Join(filePath, name))
	if err != nil {
		m.flow.errMsg = append(m.flow.errMsg, "读取文件："+err.Error())
		return err
	}
	m.flow.outByte[node.Id] = bs
	return nil
}
